package com.decent.ejfadmin.user.controller;

import com.decent.ejfadmin.common.bean.*;
import com.decent.ejfadmin.common.enums.SubmitCardApplyEnum;
import com.decent.ejfadmin.common.enums.SupRedisKey;
import com.decent.ejfadmin.common.exception.OperateFailException;
import com.decent.ejfadmin.user.service.UserService;
import com.decent.ejfadmin.utils.SimpleCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Stream;

/**
 * 会员列表
 *
 * @author weicx
 * @date 2018/07/24
 */
@RestController
@RequestMapping("UserController")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询会员信息
     *
     * @param supUser   会员实体
     * @param page      分页组件
     * @param startTime 查询开始时间
     * @param endTime   查询结束时间
     * @param include   0包含，1剔除
     * @param auditType 供卡审核状态
     * @return Page
     */
    @RequestMapping("getUser")
    public Page getUser(SupUser supUser, Page page, String startTime, String endTime, Integer include, String auditType) {
        try {
            return userService.getUser(supUser, page, startTime, endTime, include, auditType);
        } catch (Exception e) {
            log.error("会员列表: [{}]", e, e);
            page.setResultList(new ArrayList<>());
            page.setTotal(0);
            return page;
        }
    }

    /**
     * 分页查询会员操作记录
     *
     * @param page   当前页数
     * @param size   每页条数
     * @param userId 会员id
     * @return page
     */
    @SuppressWarnings("JavadocReference")
    @RequestMapping("queryUserRecordPage")
    public Page<SupUserRecord> queryUserRecordPage(Page<SupUserRecord> page, Long userId) {
        try {
            return userService.queryUserRecordPage(page, userId);
        } catch (Exception e) {
            log.error("会员操作记录列表异常", e);
            page.setResultList(Collections.emptyList());
            page.setTotal(0);
            return page;
        }
    }

    /**
     * 审核会员供卡申请
     *
     * @param userId 会员id
     * @param apply  SUCCESS：审核成功；FAIL：审核失败；
     * @param remark 审核备注
     * @return MessageBean
     */
    @RequestMapping("auditSubmitCardApply")
    public MessageBean auditSubmitCardApply(Long userId, SubmitCardApplyEnum apply, String remark) {
        if (userId == null) {
            return MessageBean.fail("请选择要审核的会员");
        }
        if (apply == null) {
            return MessageBean.fail("请选择审核操作");
        }
        if (SubmitCardApplyEnum.FAIL == apply && StringUtils.isBlank(remark)) {
            return MessageBean.fail("请输入审核备注");
        }
        try {
            return userService.auditSubmitCardApply(userId, apply, remark);
        } catch (Exception e) {
            log.error("审核会员供卡申请[{}][{}]异常", userId, apply, e);
            return MessageBean.fail();
        }
    }

    /**
     * 会员锁定: 锁定后会员无法登陆（密码错误过多解绑）
     *
     * @param account 会员编号
     * @param state   1 锁定 0 解锁
     * @return MessageBean
     */
    @RequestMapping("unLockUser")
    public MessageBean unLockUser(String account, Integer state) {
        try {
            if (StringUtils.isBlank(account) || state == null) {
                return MessageBean.fail();
            }
            return userService.unLockUser(account, state);
        } catch (Exception e) {
            log.warn("会员[{}]解锁/锁定[{}]出现异常[{}]", account, state, e);
            return MessageBean.fail();
        }
    }

    /**
     * 会员解锁
     *
     * @param ip 会员ip
     * @return MessageBean
     */
    @RequestMapping("unLockUserIp")
    public MessageBean unLockUserIp(String ip) {
        try {
            if (StringUtils.isBlank(ip)) {
                return MessageBean.fail("请输入ip");
            }
            return userService.unLockUserIp(ip);
        } catch (Exception e) {
            log.warn("会员[{}]IP解锁出现异常[{}]", ip, e);
            return MessageBean.fail();
        }
    }

    /**
     * 查询注册黑名单
     *
     * @param accountOrIp 手机号/ip
     * @param type        查询类型，Ip/No
     * @return list
     */
    @RequestMapping("queryRegisterBlackList")
    public List<HashMap<String, Object>> queryRegisterBlackList(String accountOrIp, String type) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(type)) {
                return new ArrayList<>();
            }
            return userService.queryRegisterBlackList(accountOrIp, type);
        } catch (Exception e) {
            log.warn("查询注册黑名单异常", e);
            return new ArrayList<>();
        }
    }

    /**
     * 移除注册黑名单
     *
     * @param data 黑名单信息
     * @return MessageBean
     */
    @RequestMapping("removeBlackList")
    public MessageBean removeBlackList(String data) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(data)) {
                return MessageBean.fail("请选择要删除的记录");
            }

            userService.removeBlackList(data);
            return MessageBean.success();
        } catch (Exception e) {
            log.warn("查询注册黑名单异常", e);
            return MessageBean.fail("系统异常");
        }
    }

    /**
     * 新增IP黑名单
     *
     * @param ip
     * @return
     */
    @RequestMapping("createIpBlack")
    public MessageBean createIpBlack(String ip) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(ip)) {
                return MessageBean.fail("请输入要绑定的IP");
            }
            userService.createIpBlack(ip);
            return MessageBean.success();
        } catch (Exception e) {
            log.warn("绑定IP黑名单异常", e);
            return MessageBean.fail("绑定IP黑名单异常");
        }
    }

    /**
     * 导出Ip黑名单信息
     *
     * @param accountOrIp
     * @param type
     * @param response
     * @return
     */
    @RequestMapping("downloadUserInfoList")
    public void downloadUserInfoList(String accountOrIp, String type, HttpServletResponse response) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(accountOrIp)) {
                return;
            }
            userService.downloadUserInfoList(accountOrIp, type, response);
        } catch (Exception ex) {
            log.warn("导出IP黑名单信息异常{}", ex, ex);
            throw new OperateFailException(ex.getMessage());
        }
    }

    /**
     * 修改会员支付密码
     *
     * @param account 会员编号
     * @param payPwd  支付密码
     * @return MessageBean
     */
    @RequestMapping("updatePayPwd")
    public MessageBean updatePayPwd(String account, String payPwd) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(account) || org.apache.commons.lang.StringUtils.isBlank(payPwd)) {
                return MessageBean.fail("请输入会员编号和支付密码");
            }
            payPwd = org.apache.commons.lang.StringUtils.trimToEmpty(payPwd);
            int standardPayPwdLength = 6;
            if (StringUtils.length(payPwd) != standardPayPwdLength || !org.apache.commons.lang.StringUtils.isNumeric(payPwd)) {
                return MessageBean.fail("支付密码必须为6位纯数字！");
            }
            return userService.updatePayPwd(account, payPwd);
        } catch (Exception e) {
            log.warn("修改支付密码失败[{}]", account, e);
            return MessageBean.fail();
        }
    }

    /**
     * 查询同一ip注册多少账号
     *
     * @param ip ip
     * @return
     */
    @RequestMapping("getUserByIP")
    public List<SupUser> getUserByIp(String ip) {
        try {
            return userService.queryUserByIp(ip);
        } catch (Exception e) {
            log.warn("查询同一ip注册账号异常: [{}]", ip, e);
            return Collections.emptyList();
        }
    }

    /**
     * 查询会员权限
     *
     * @param supUser 会员实体
     * @return
     */
    @RequestMapping("queryPrivilege")
    public SupPrivilege queryPrivilege(SupUser supUser) {
        try {
            return userService.queryPrivilege(supUser);
        } catch (Exception e) {
            log.warn("查询会员权限异常: [{}]", e);
            return null;
        }
    }

    /**
     * 修改会员信息
     *
     * @param supUser 会员
     * @return MessageBean
     */
    @RequestMapping("updateSupUser")
    public MessageBean updateSupUser(SupUser supUser) {
        if (supUser.getUserId() == null) {
            return MessageBean.fail("参数错误");
        }
        if (StringUtils.isBlank(supUser.getAccount())) {
            return MessageBean.fail("会员编号不能为空");
        }
        if (StringUtils.isBlank(supUser.getSupInfo().getName())) {
            return MessageBean.fail("会员名称不能为空");
        }
        if (supUser.getSupplyModel() == null) {
            return MessageBean.fail("销卡模板不能为空");
        }
        return userService.updateSupUser(supUser);
    }

    /**
     * 修改会员权限
     *
     * @param supPrivilege 会员权限
     * @return MessageBean
     */
    @RequestMapping("updatePrivilege")
    public MessageBean updatePrivilege(SupPrivilege supPrivilege) {
        try {
            if (supPrivilege.getUserId() == null) {
                return MessageBean.fail("参数错误");
            }
            return userService.updatePrivilege(supPrivilege);
        } catch (Exception e) {
            log.error("查询会员权限异常: ", e);
            return null;
        }
    }

    /**
     * 批量会员状态变更
     *
     * @param userIds   会员id
     * @param status    状态 0：开启 1：关闭
     * @param privilege accountStatus 账号状态  apiState：接口状态
     * @return
     */
    @RequestMapping("updateUserStatus")
    public MessageBean updateUserStatus(Long[] userIds, Integer status, String privilege) {
        try {
            return userService.updateUserStatus(userIds, status, privilege);
        } catch (Exception e) {
            log.warn("批量会员状态变更异常: [{}]", e);
            return null;
        }
    }

    /**
     * 重置登录密码
     *
     * @param userId 会员id
     * @return
     */
    @RequestMapping("resetUserLoginPwd")
    public MessageBean resetUserLoginPwd(Long userId) {
        try {
            return userService.resetUserLoginPwd(userId);
        } catch (Exception e) {
            log.warn("重置登录密码异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 新建会员
     *
     * @param supUser 会员
     * @return MessageBean
     */
    @RequestMapping("insertSupUser")
    public MessageBean insertSupUser(SupUser supUser) {
        try {
            if (StringUtils.isBlank(supUser.getAccount())) {
                return MessageBean.fail("会员编号不能为空");
            }
            if (StringUtils.isBlank(supUser.getSupInfo().getName())) {
                return MessageBean.fail("会员名称不能为空");
            }
            if (Objects.isNull(supUser.getDailySupplyLimit())) {
                return MessageBean.fail("会员名称不能为空");
            }
            if (supUser.getSupplyModel() == null) {
                return MessageBean.fail("销卡模板不能为空");
            }
            return userService.insertSupUser(supUser);
        } catch (Exception e) {
            log.warn("新增会员信息异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 会员信息导出
     *
     * @param supUser   会员实体
     * @param startTime 查询开始时间
     * @param endTime   查询结束时间
     * @param include   0包含，1剔除
     * @param auditType 审核状态
     * @return
     */
    @RequestMapping("downLoad")
    public void downLoad(SupUser supUser, String startTime, String endTime, Integer include, String auditType, HttpServletResponse response) {
        ServletOutputStream writer = null;
        try {
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            writer = response.getOutputStream();
            userService.downLoad(supUser, startTime, endTime, include, auditType, response);
        } catch (Exception e) {
            log.warn("会员信息导出出错[{}]", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 开启api会员自动异步
     *
     * @param userId 会员id
     * @return
     */
    @RequestMapping("autoAsyn")
    public MessageBean autoAsyn(Long userId) {
        try {
            return userService.autoAsyn(userId);
        } catch (Exception e) {
            log.warn("开启api会员自动异步异常: [{}]", userId, e);
            return MessageBean.fail(e.getMessage());
        }
    }

    @RequestMapping("callBack")
    public String callBack() {
        return "OK";
    }


    /**
     * 批量导入IP黑名单
     *
     * @param ips IP
     * @return
     */
    @RequestMapping("upLoadIpBlack")
    public MessageBean upLoadIpBlack(String ips) {
        try {
            if (org.apache.commons.lang.StringUtils.isBlank(ips)) {
                return MessageBean.fail("请输入要导入的IP");
            }
            String[] ipArray = ips.split(",");
            Stream.of(ipArray).forEach(ip -> {
                SimpleCacheUtil.setObject(SupRedisKey.SUP_RIP + ip, 11);
            });
            return MessageBean.success();
        } catch (Exception e) {
            log.warn("导入IP黑名单异常", e);
            return MessageBean.fail("导入IP黑名单异常");
        }
    }

    /**
     * 生成会员秘钥
     *
     * @return
     */
    @RequestMapping("getUserKey")
    public String getUserKey() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "").trim();
    }


    /**
     * 修改权益信用分
     *
     * @param userIds      会员id
     * @param equityCredit 权益信用分
     * @return
     */
    @RequestMapping("updateEquityCredit")
    public MessageBean updateEquityCredit(Long[] userIds, BigDecimal equityCredit, String remark) {
        try {
            if (userIds == null || equityCredit == null || StringUtils.isBlank(remark)) {
                return MessageBean.fail("参数错误");
            }
            return userService.updateEquityCredit(userIds, equityCredit, remark);
        } catch (Exception e) {
            log.warn("修改权益信用分异常", e);
            return MessageBean.fail("修改权益信用分异常");
        }
    }

    /**
     * 查询权益信用分修改记录
     *
     * @param equityCreditModify 会员实体
     * @param page               分页组件
     * @param startTime          查询开始时间
     * @param endTime            查询结束时间
     * @return
     */
    @RequestMapping("queryEquityCreditModify")
    public Page queryEquityCreditModify(EquityCreditModify equityCreditModify, Page page, String startTime, String endTime) {
        try {
            return userService.queryEquityCreditModify(equityCreditModify, page, startTime, endTime);
        } catch (Exception e) {
            log.warn("查询权益信用分修改记录: [{}]", e);
            page.setResultList(new ArrayList<>());
            page.setTotal(0);
            return page;
        }
    }

    /**
     * 开启api会员自动异步
     *
     * @param userId 会员id
     * @return
     */
    @RequestMapping("autoUserAsyn")
    public MessageBean autoUserAsyn(Long userId) {
        try {
            SimpleCacheUtil.removeObject(SupRedisKey.AUTO_ASYN.toString() + userId);
            SimpleCacheUtil.removeObject(SupRedisKey.ASYN_ABNORMAL_COUNT.toString() + userId);
            return MessageBean.success();
        } catch (Exception e) {
            log.warn("开启api会员自动异步异常: [{}]",userId, e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 会员佣金展示状态获取 true 开启 false 关闭
     *
     * @return
     */
    @RequestMapping(value = "getCommissionStatus")
    public boolean getCommissionStatus() {
        try {
            return userService.getCommissionStatus();
        } catch (Exception e) {
            log.warn("getCommissionStatus occurs error Internal Server Error  ", e);
            return true;
        }
    }

    /**
     * 会员佣金展示 开关
     *
     * @param status
     * @return
     */
    @RequestMapping(value = "updateCommissionStatus")
    public MessageBean updateCommissionStatus(Integer status) {
        MessageBean messageBean = MessageBean.success();
        try {
            userService.updateCommissionStatus(status);
        } catch (Exception e) {
            messageBean = MessageBean.fail();
            log.warn("updateCommissionStatus occurs error Internal Server Error  ", e);
        }
        return messageBean;
    }
}
